package com.example.lijuan.myapplication.UI.Fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.PolylineOptions;
import com.example.lijuan.myapplication.R;
import com.example.lijuan.myapplication.Service.TripServices;
import com.example.lijuan.myapplication.Util.Constants;
import com.example.lijuan.myapplication.module.Location;
import com.example.lijuan.myapplication.module.Trip;
import com.example.lijuan.myapplication.module.TripSummary;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;

public class FragmentCarTrip extends Fragment {
    View rootView;
    private MapView tripMapView;
    protected AMap aMap;
    private Marker deviceMarker;
    private TextView textViewLastTripDate;
    private TextView textViewLastTripMile;
    private TextView textViewLastTripTime;
    private ArrayList<LatLng> points;
    private Double longMax, longMin, latMax, latMin, longCenter, latCenter;
    private Button btnTripHistory;
    private FragmentManager fragmentManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null == fragmentManager) {
            fragmentManager = getFragmentManager();
        }
        longMax = longMin = latMax = latMin = 0.0;
        Bundle bundle = getArguments();
        if (bundle != null) {
            Trip trip = (Trip) bundle.getSerializable("trips");
            List<Location> point = trip.getLocations();
            points = new ArrayList<>();
            Iterator iterator = point.iterator();
            while (iterator.hasNext()) {
                Location location = (Location) iterator.next();
                Double latitude = Double.parseDouble(location.getLatitude());
                Double longitude = Double.parseDouble(location.getLongitude());

                points.add(new LatLng(latitude, longitude));

            }
//            LatLng latLngCenter = getCenter(points);
//            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLngCenter));
//            addPLines(points);
        }
    }

    @Override
    public void onResume() {
        if (tripMapView != null) {
            tripMapView.onResume();
        }
        super.onResume();
    }

    @Override
    public void onPause() {

        if (tripMapView != null) {
            tripMapView.onPause();
        }
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_car_trip, container, false);

        tripMapView = (MapView) rootView.findViewById(R.id.trip_info_map);
        textViewLastTripDate = (TextView) rootView.findViewById(R.id.trip_summary_date);
        textViewLastTripMile = (TextView) rootView.findViewById(R.id.trip_summary_mile);
        textViewLastTripTime = (TextView) rootView.findViewById(R.id.trip_summary_time);

        tripMapView.onCreate(savedInstanceState);
        initMap();
        LatLng latLng = new LatLng(39.157419, 117.334671);
        drawDeviceMarker(latLng);
        longMax = longMin = latMax = latMin = 0.0;
        if (points != null) {
            LatLng latLngCenter = getCenter(points);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLngCenter));
            addPLines(points);
        }
        btnTripHistory = (Button) rootView.findViewById(R.id.btn_trip_history);
        btnTripHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showListViewFragment();
            }
        });
        setUpTripInfo();
        return rootView;
    }

    private void showListViewFragment() {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.replace(R.id.fragment_car_trip, FragmentTripHistoryList.newInstance());
        ft.commit();
    }

    protected void initMap() {
        if (aMap == null) {
            aMap = tripMapView.getMap();
            aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
            aMap.getUiSettings().setCompassEnabled(true);// 设置指南针
            aMap.getUiSettings().setScaleControlsEnabled(true);// 设置比例尺
        }
    }

    public void drawDeviceMarker(LatLng latLng) {
        if (deviceMarker == null) {
//            BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher);
            BitmapDescriptor icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE);
            if (icon != null) {
                deviceMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon).position(latLng));
            }
        }
        if (latLng.longitude != 0.0 && latLng.latitude != 0.0) {
            deviceMarker.setPosition(latLng);

            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        }
    }

    public void addPLines(ArrayList<LatLng> points) {
        aMap.addPolyline((new PolylineOptions()).addAll(points)
                .width(10)
                .geodesic(true).color(Color.RED));

    }

    public LatLng getCenter(ArrayList<LatLng> points) {
        Iterator iterator = points.iterator();
        while (iterator.hasNext()) {
            LatLng ll = (LatLng) iterator.next();
            if (longMax == 0 && longMin == 0 && latMax == 0 && latMin == 0) {
                longMax = longMin = ll.longitude;
                latMax = latMin = ll.latitude;
            } else {
                if (ll.longitude > longMax) {
                    longMax = ll.longitude;
                } else if (ll.longitude < longMin) {
                    longMin = ll.longitude;
                }
                if (ll.latitude > latMax) {
                    latMax = ll.latitude;
                } else if (ll.latitude < latMin) {
                    latMin = ll.latitude;
                }
            }
        }
        longCenter = (longMax + longMin) / 2;
        latCenter = (latMax + latMin) / 2;
        LatLng latLngCenter = new LatLng(latCenter, longCenter);
        return latLngCenter;
    }

    private void setUpTripInfo() {
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("Content-Type", "application/json").addHeader("header", Constants.ACCEPT).build();
                return chain.proceed(request);
            }
        };
        // Add the interceptor to OkHttpClient
        OkHttpClient client = new OkHttpClient();
        client.interceptors().add(interceptor);

        // Set the custom client when building adapter
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.SERVER_ADDRESS)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        //
        TripServices tripServices = retrofit.create(TripServices.class);
        Call<TripSummary> call = tripServices.getTrip("CAR_A00A000002");
        call.enqueue(new Callback<TripSummary>() {

            @Override
            public void onResponse(retrofit.Response<TripSummary> response, Retrofit retrofit) {
                System.out.println("TripSummery : " + response.toString());
                TripSummary tripSummary = response.body();
                // update UI
                textViewLastTripMile.setText(getString(R.string.trip_summary_mile) + " " + Double.toString(tripSummary.getThisMileage()) + getString(R.string.km));
                textViewLastTripDate.setText(getString(R.string.trip_summary_date) + " " + tripSummary.lastLocation.getLocationTime());
                textViewLastTripTime.setText(getString(R.string.trip_summary_time) + " " + formatTime(tripSummary.getThisDriveTime()));
            }

            @Override
            public void onFailure(Throwable t) {
                System.out.println("Error : " + t.toString());
            }

            private String formatTime(double second) {
                String result = "";
                int hour = (int) (second / 3600);
                int minute = (int) ((second - hour * 3600) / 60);
                result = Integer.toString(hour) + getString(R.string.hour) + Integer.toString(minute) + getString(R.string.minute);
                return result;
            }
        });
    }
}
